package com.csu.csumall.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csu.csumall.VO.OrderItemVO;
import com.csu.csumall.entity.Order;
import com.csu.csumall.entity.OrderItem;
import com.csu.csumall.entity.User;
import com.csu.csumall.mapper.OrderItemMapper;
import com.csu.csumall.mapper.OrderMapper;
import com.csu.csumall.service.IOrderItemVOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service("orderItemVOService")
public class OrderItemVOServiceImp implements IOrderItemVOService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;

    @Autowired
    public OrderItemVOServiceImp(OrderMapper orderMapper, OrderItemMapper orderItemMapper) {
        this.orderMapper = orderMapper;
        this.orderItemMapper = orderItemMapper;
    }

    @Override
    public List<OrderItemVO> list(User user, int page, int size) {

        int userId = user.getId();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.eq("user_id", userId)
                .orderByAsc("create_time");

        IPage<Order> orderIPage = orderMapper.selectPage(new Page<>(page, size), orderQueryWrapper);
        List<Order> orderList = orderIPage.getRecords();
        List<OrderItemVO> orderItemVOList = new ArrayList<>();

        orderList.forEach(order -> {
            List<OrderItem> orderItemList = orderItemMapper.selectList(
                    new QueryWrapper<OrderItem>().eq("order_no", order.getOrderNo()));
            OrderItemVO orderItemVO = new OrderItemVO(order, orderItemList);
            orderItemVOList.add(orderItemVO);
        });

        return orderItemVOList;
    }
    
    @Override
    public List<OrderItemVO> list(User user, int status, int page, int size) {

        int userId = user.getId();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.eq("user_id", userId)
                .eq("status", status)
                .orderByAsc("create_time");

        IPage<Order> orderIPage = orderMapper.selectPage(new Page<>(page, size), orderQueryWrapper);
        List<Order> orderList = orderIPage.getRecords();
        List<OrderItemVO> orderItemVOList = new ArrayList<>();

        orderList.forEach(order -> {
            List<OrderItem> orderItemList = orderItemMapper.selectList(
                    new QueryWrapper<OrderItem>().eq("order_no", order.getOrderNo()));
            OrderItemVO orderItemVO = new OrderItemVO(order, orderItemList);
            orderItemVOList.add(orderItemVO);
        });

        return orderItemVOList;
    }

}
